<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true">
      <el-form-item label="项目名称" prop="projectName">
        <el-input
          v-model="queryParams.projectName"
          placeholder="请输入项目名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属组织架构" prop="ipdName">
        <el-input
          v-model="queryParams.ipdName"
          placeholder="请输入所属组织架构"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['project:project:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['project:project:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['project:project:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['project:project:import']"
        >导入</el-button>
      </el-col>
     <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['project:project:export']"
        >导出</el-button>
      </el-col>-->
    </el-row>

    <el-table v-loading="loading" :data="projectList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" align="center" />
      <el-table-column label="项目名称" align="center" prop="projectName" />
      <el-table-column label="详细地址" align="center" prop="address" />
      <el-table-column label="所属组织机构" align="center" prop="deptName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['project:project:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['project:project:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改项目管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="项目名称" prop="projectName">
          <el-input :maxlength="64" v-model="form.projectName" placeholder="请输入项目名称" />
        </el-form-item>
        <el-form-item label="所属招商部" prop="ipdName">
          <vue-treeselect v-model="form.ipdName" :options="deptOptions" :disable-branch-nodes="true" :show-count="true" placeholder="请选择招商部" />
        </el-form-item>
        <el-form-item label="省市区" prop="coordinate">

          <v-distpicker :province="select.province" :city="select.city" :area="select.area" @selected="setCity"></v-distpicker>
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入详细地址" />

        </el-form-item>

        <el-form-item label="项目类型">

          <el-select
            v-model="projectType"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="请选择项目类型">
            <el-option
              v-for="item in typeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="建筑面积" prop="area">
          <el-input oninput="if(value.length > 11) value = value.slice(0,16)" type="number" v-model="form.area" placeholder="请输入建筑面积" />
        </el-form-item>
        <el-form-item label="交付运营时间" prop="deliverTime">
          <el-date-picker clearable size="small" style="width: 200px"
            v-model="form.deliverTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择交付运营时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="物业公司" prop="property">
          <el-input v-model="form.property" placeholder="请输入物业公司" />
        </el-form-item>
        <el-form-item label="物业费(元/㎡·月)" prop="propertyMoney">
          <el-input oninput="if(value.length > 11) value = value.slice(0,16)" type="number" v-model="form.propertyMoney" placeholder="请输入物业费(元/㎡·月)" />
        </el-form-item>
        <el-form-item label="停车位数量" prop="parking">
          <el-input oninput="if(value.length > 11) value = value.slice(0,16)" type="number" v-model="form.parking" placeholder="请输入停车位数量" />
        </el-form-item>

        <el-form-item label="交付标准" prop="deliveryStandard">
          <el-select v-model="form.deliveryStandard" placeholder="请选择交付标准">
            <el-option
              v-for="dict in deliveryOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="标准层面积" prop="standardLayerArea">
          <el-input oninput="if(value.length > 11) value = value.slice(0,16)"  type="number" v-model="form.standardLayerArea" placeholder="请输入标准层面积" />
        </el-form-item>
        <el-form-item label="楼层层高/m" prop="standardLayerHeight">
          <el-input oninput="if(value.length > 11) value = value.slice(0,16)" type="number" v-model="form.standardLayerHeight" placeholder="请输入楼层层高/m" />
        </el-form-item>
        <el-form-item label="项目简介" prop="introduction">
          <Editor v-model="form.introduction" />
        </el-form-item>
        <el-form-item label="外观图" prop="image" style="margin-top:100px">
          <el-upload
            list-type="picture-card"
            :limit="9"
            :file-list="fileList"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :action="uploadImgUrl"
            name="file"
            :headers="headers"
            :show-file-list="true"
            :on-success="quillImgSuccess"
            :on-error="uploadError"
            :before-upload="quillImgBefore"
            accept='.jpg,.jpeg,.png,.gif'
            >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 项目导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的项目数据
          <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProject, getProject, delProject, addProject, updateProject, exportProject,importTemplate } from "@/api/project/project";
import Editor from '@/components/Editor';
import { getToken } from '@/utils/auth'
import VDistpicker from 'v-distpicker'
import { treeselect } from "@/api/system/dept";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import VueTreeselect from "@riophae/vue-treeselect/src/components/Treeselect";
export default {
  components: {
    VueTreeselect,
    Editor,
    VDistpicker
  },
  name: "Project",
  data() {
    return {
      // 遮罩层
      loading: true,
      //项目信息
      dept:{},
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 项目管理表格数据
      projectList: [],
      // 弹出层标题
      title: "",
      //招商部字典
      ipdNameOptions:[],
      // 部门树选项
      deptOptions: undefined,
      //交付状态
      deliveryOptions:[],
      //项目类别
      // typeOptions:[],
      typeOptions: [{
          value: '市级孵化',
          label: '市级孵化'
        }, {
          value: '商业综合体',
          label: '商业综合体'
        }, {
          value: '5A甲级写字楼',
          label: '5A甲级写字楼'
        }],
      //项目类型
      projectType:[],
      //默认地址选择
      select: { },
      citys:{},
      // 是否显示弹出层
      open: false,
      // 项目导入参数
      upload: {
        // 是否显示弹出层（项目导入）
        open: false,
        // 弹出层标题（项目导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/project/project/importData"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectName: undefined,
        ipdName: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        projectName:[{required: true, message: '请输入项目名称', trigger: 'blur'}],
        ipdName:[{required: true, message: '请选择所属招商部', trigger: 'change'}],
        coordinate:[{required: true, message: '请选择省市区', trigger: 'change'}],
        address:[{required: true, message: '请输入详细地址', trigger: 'blur'}],
        introduction:[{required: true, message: '请输入项目简介', trigger: 'blur'}],
        image:[{required: true, message: '请输入图片', trigger: 'blur'}],
      },
      //富文本
      editorOption: {},
      //图片上传
      fileList:[],
      dialogImageUrl: '',
      dialogVisible: false,
      uploadImgUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传的图片服务器地址
      headers: {
        Authorization: 'Bearer ' + getToken()
      }
    };
  },
  created() {
    this.getList();
    this.getTreeselect();
    this.getDicts("am_peoject_delivery_standard").then(response => {
      this.deliveryOptions = response.data;
    });

    var user=JSON.parse(localStorage.getItem("user"))
    console.log(user.dept)
    this.dept=user.dept
  },
  methods: {
    /** 查询项目管理列表 */
    getList() {
      this.loading = true;
      listProject(this.queryParams).then(response => {
        this.projectList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        this.deptOptions = response.data;
      });
    },
    // 装修字典翻译
    decoratingFormat(row, column) {
      return this.selectDictLabel(this.deliveryOptions, row.decorating);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        projectCode: undefined,
        projectName: undefined,
        ipdName: undefined,
        address: undefined,
        coordinate: undefined,
        area: undefined,
        scale: undefined,
        rebateAmount: undefined,
        deliverTime: undefined,
        property: undefined,
        propertyMoney: undefined,
        parking: undefined,
        deliveryStandard: undefined,
        projectType: undefined,
        standardLayerArea: undefined,
        standardLayerHeight: undefined,
        introduction: undefined,
        image: undefined,
        del: undefined,
        createTime: undefined,
        modifiedTime: undefined,
        coordinate:undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加项目管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.fileList=[]
      const id = row.id || this.ids
      getProject(id).then(response => {
        this.form = response.data;
        if(response.data.projectType){
          let arrs=response.data.projectType.split(',')
          this.projectType=arrs

        }
        if(response.data.coordinate){
          var citys=response.data.coordinate.split(',')
          console.log(citys)
          this.select={
            province:citys[0],
            city:citys[1],
            area:citys[2],

          }
          this.citys={
            province:{
              code:1,
              value:citys[0]
            },
            city:{
              code:2,
              value:citys[1]
            },
            area:{
              code:3,
              value:citys[2]
            },
          }
        }
        var list=[]
        var arr=response.data.image.split(',')
        if(arr.length){
          arr.forEach(item=>{
            list.push({name:item,url:item})
          })
        }
        this.fileList=list
        this.open = true;
        this.title = "修改项目管理";
      });
    },
    /** 提交按钮 */
    submitForm: function() {

      if(this.citys.area&&this.citys.area.code){
        this.form.coordinate=this.citys.province.value+','+this.citys.city.value+","+this.citys.area.value
        // if(this.form.address){
        //   this.form.address=this.citys.province.value+','+this.citys.city.value+","+this.citys.area.value+","+this.form.address
        // }
      }

      if(this.projectType.length){
        this.form.projectType=this.projectType.join(",")
      }
      var img=[]
      if(this.fileList.length){
        this.fileList.forEach(item=>{
          img.push(item.url)
        })
      }
      this.form.image=img.join(",")

      console.log(this.form)
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateProject(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
                this.fileList=[]
              }
            });
          } else {
            addProject(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
                this.fileList=[]
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('删除后无法撤销，请确认!', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delProject(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有项目管理数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportProject(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    },
    // 图片上传前
    quillImgBefore(file) {
      let fileType = file.type;
			if(fileType === 'image/jpeg' || fileType === 'image/png'){
				return true;
			}else {
				this.$message.error('请插入图片类型文件(jpg/jpeg/png)');
				return false;
			}
    },

    quillImgSuccess(res, file) {
      // res为图片服务器返回的数据
      // 如果上传成功
      if (res.code == 200) {
        var list=[...this.fileList]
        list.push({name:res.fileName,url:res.url})
        console.log(list)
        this.fileList=list
      } else {
        this.$message.error("图片上传失败");
      }
    },
    // 图片上传失败
    uploadError() {
      // loading动画消失
      this.$message.error("图片上传失败");
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
      var list=[...this.fileList]
      var index=0
      for(var i in list){

        if(list[i].url===file.url){
          index=i
        }
      }
      list.splice(index*1,1)
      this.fileList=list
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "项目导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      importTemplate().then(response => {
        this.download(response.msg);
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    //选择省市区
    setCity(data){
      this.citys=data
    }
  }
};
</script>
